
//  Created by DJI on 7/7/15.
//  Copyright (c) 2015 DJI. All rights reserved.
//

#import "DJIMapController.h"
#import "BaseWebViewVC.h"
@interface DJIMapController ()
/** 网页控制器*/
@property (nonatomic, strong)BaseWebViewVC *webVC;
@property (nonatomic, copy) NSMutableString *intputStr;

/** 无人机与出发点距离（保留小数点后一位）*/
@property (nonatomic, assign) CGFloat sDistance;
/** 无人机飞行距离（保留小数点后一位）*/
@property (nonatomic, assign) CGFloat fDistance;
/** 飞行时间定时器*/
@property (nonatomic, strong) NSTimer *flyTimer;
/** 飞行器的速度*/
@property (nonatomic, assign) int     flyS;
/** 飞行器飞完整个航程说需要的时间*/
@property (nonatomic, assign) int     totalTime;
/** 飞行器多少秒拍一下照片*/
@property(nonatomic, assign) CGFloat   singleTime2TakePhoto;
@end

@implementation DJIMapController

- (instancetype)init
{
    if (self = [super init]) {
        
        self.editPoints = [[NSMutableArray alloc] init];
        self.latArr = [[NSMutableArray alloc] init];
        self.lngArr = [[NSMutableArray alloc] init];
        self.flyS = 4;//暂定飞行器的速度是8m/s
    }
    
    return self;
}

- (void)addPoint:(CGPoint)point withMapView:(MKMapView *)mapView
{
    CLLocationCoordinate2D coordinate = [mapView convertPoint:point toCoordinateFromView:mapView];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    [_editPoints addObject:location];
    [_latArr addObject:[NSString stringWithFormat:@"%f",location.coordinate.latitude]];
    
    [_lngArr addObject:[NSString stringWithFormat:@"%f",location.coordinate.longitude]];
    MKPointAnnotation* annotation = [[MKPointAnnotation alloc] init];
    annotation.coordinate = location.coordinate;
    [mapView addAnnotation:annotation];
    
}

/**
 *画飞行航线
 */
- (void)drawFlyDoneLine {
    NSMutableString *mutStr = [[NSMutableString alloc] init];
    
    @WeakObj(self);
    for (int i = 0 ; i < _latArr.count; i ++) {
        NSString *str = [NSString stringWithFormat:@"%@,%@",_latArr[i],_lngArr[i]];
        if (i == 0) {
              [mutStr appendString:[NSString stringWithFormat:@"%@",str]];
        }else {
              [mutStr appendString:[NSString stringWithFormat:@",%@",str]];
        }
    }
    //NSLog(@"mutStr----%@",mutStr);

    if (!_webVC) {// *把飞行的side overlay和相机旋转角度传给web
        _webVC = [[BaseWebViewVC alloc] init];

    }
    _webVC.latLngStr = mutStr;
    [_webVC creatWebView];
    _webVC.airCraftLinePointsBlcok = ^(NSString *str) {
        selfWeak.airCraftLineBlock(str);
    };
}

/**
 *重置航线
 */
- (void)reSetAirCraftLine:(NSString *)angle FlyHeight:(NSString *)flyHeight {
    @WeakObj(self);
    [_webVC reSetAirCraftLine:angle FlyHeight:flyHeight];
    _webVC.airCraftLinePointsBlcok = ^(NSString *str) {
        selfWeak.airCraftLineBlock(str);
    };
}

- (void)cleanAllPointsWithMapView:(MKMapView *)mapView
{
    [_latArr removeAllObjects];
    [_lngArr removeAllObjects];

    [_editPoints removeAllObjects];
    NSArray* annos = [NSArray arrayWithArray:mapView.annotations];
    for (int i = 0; i < annos.count; i++) {
        id<MKAnnotation> ann = [annos objectAtIndex:i];
        
        if (![ann isEqual:self.aircraftAnnotation]) { //Add it to check if the annotation is the aircraft's and prevent it from removing
            [mapView removeAnnotation:ann];
        }
        
    }
}

- (NSArray *)wayPoints
{
    return self.editPoints;
}

-(void)updateAircraftLocation:(CLLocationCoordinate2D)location withMapView:(MKMapView *)mapView
{
    if (self.aircraftAnnotation == nil) {
        self.aircraftAnnotation = [[DJIAircraftAnnotation alloc] initWithCoordiante:location];
        [mapView addAnnotation:self.aircraftAnnotation];
    }
    
    [self.aircraftAnnotation setCoordinate:location];

    
    MKMapPoint point1 = MKMapPointForCoordinate(CLLocationCoordinate2DMake(location.latitude,location.longitude));
    
    MKMapPoint point2 = MKMapPointForCoordinate(CLLocationCoordinate2DMake(_coorS.latitude, _coorS.longitude));
    CLLocationDistance distance = MKMetersBetweenMapPoints(point1, point2);
    CGFloat dis = distance;
    NSString *sDis= [NSString stringWithFormat:@"%.1f",dis];
    self.sDistance = [sDis floatValue];//取小数点后一位，无人机距离开始点距离
    if (self.sDistance < 1 && self.isFinishedSet) {
        [ToolHelper notifyError:@"到起飞点"];
        self.isCouldTakePhoto = YES;
        
    }

    if (self.isCouldTakePhoto) {
        //唤起定时器
        //定时执行 唤起语音的操作
        if (!_flyTimer && self.singleTime2TakePhoto > 0.2) {
             [ToolHelper notifyError:[NSString stringWithFormat:@"拍摄间隔 %f",self.singleTime2TakePhoto]];
            _flyTimer = [NSTimer timerWithTimeInterval:self.singleTime2TakePhoto target:self selector:@selector(flyTimerRecord) userInfo:nil repeats:YES];
            // 将定时器添加到runloop中，否则定时器不会启动
            [[NSRunLoop mainRunLoop] addTimer:_flyTimer forMode:NSRunLoopCommonModes];
            [_flyTimer fire];
        }
        //拍照传值
        if (self.sDisAndTotalDisBlock) {
            self.sDisAndTotalDisBlock([NSString stringWithFormat:@"%f",self.singleTime2TakePhoto],[NSString stringWithFormat:@"%d",self.totalTime]);
        }
 
    }
}

-(void)updateAircraftHeading:(float)heading
{
    if (self.aircraftAnnotation) {
        [self.aircraftAnnotation updateHeading:heading];
    }
}

/**
 *设置航线总长度
 */
- (void)setTotalLineDistance:(CGFloat )distance {
    _totalLineDistance = distance;
//    [ToolHelper notifyError:[NSString stringWithFormat:@"飞行总时间%f",_totalLineDistance]];
    //算下飞行的总时间
    self.totalTime = _totalLineDistance / self.flyS;
    //算下多少秒去拍一下
    NSString *flyHeight = [STANDARD_USER_DEFAULTS objectForKey:@"airCraftHeight"];
    self.singleTime2TakePhoto = [ToolHelper outPutCammeraPicLength:[flyHeight floatValue]] / 4;
}

/**
 *重置拍摄间隔
 */

- (void)reSetTakePhotoTime:(NSString *)frontOverLay {
    //飞行高度
    NSString *flyHeight = [STANDARD_USER_DEFAULTS objectForKey:@"airCraftHeight"];
    //frontOverLay数值
    CGFloat frontOverLayData = [frontOverLay floatValue];
    //一半的拍摄长度
    CGFloat halfPhotoLength = [ToolHelper outPutCammeraPicLength:[flyHeight floatValue]];
    NSLog(@"halfPhotoLength---%f",halfPhotoLength);
    
    //重叠区域的长度
    CGFloat overLayLength = halfPhotoLength * 2 * (frontOverLayData / 100);
    
    //余长 = 重叠区域长度减去一半的拍摄长度
    CGFloat complementLength = overLayLength - halfPhotoLength;
    //最终的两航拍点的距离 = 重叠区域的长度 - 2 * 余长
    CGFloat finalTakePhotoLength = overLayLength - 2 * complementLength;
    
    //根据飞行速度，计算飞完拍摄点间的距离，所需要的时间
    
    self.singleTime2TakePhoto = finalTakePhotoLength / 4;
    
    [ToolHelper notifyError:[NSString stringWithFormat:@"拍摄间隔%f",self.singleTime2TakePhoto]];
}

/**
 *设置航线开始点，结束点坐标
 */
- (void)setLineStartCLLocation:(CLLocation*)coorS EndCLLocation:(CLLocation*)coorE {
    
    _coorS.latitude = coorS.coordinate.latitude;
    _coorS.longitude = coorS.coordinate.longitude;
    
    _coorE.latitude = coorE.coordinate.latitude;
    _coorE.longitude = coorE.coordinate.longitude;
    
}

/**
 *清除无人机距离出发点的距离数据 和 全部航程数据
 */
- (void)clearSDisAndTotalLinDis {
    self.sDistance = 0.f;
}

/**
 *记录从开始航拍后的飞行距离
 */

- (void)flyTimerRecord {
    if(self.takePhotoBlock){
        self.takePhotoBlock();
    }

}

/**
 *停止拍照数据回调
 */
- (void)stopTakePhoto {
    self.isCouldTakePhoto = NO;
    [_flyTimer invalidate];
    _flyTimer = nil;
}

- (void)dealloc {
    [_flyTimer invalidate];
    _flyTimer = nil;
}
@end

